package xy.web.timer;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public final class TimerRunner {
	public static void start() {
		instance.startMe();
	}

	public static void stop() {
		try {
			instance.stopMe();
		} catch (Exception e) {

		}
	}

	private TimerRunner() {

	}

	private static TimerRunner instance = new TimerRunner();

	private Timer timer;

	private void startMe() {
		timer = new Timer();

		timer.schedule(new TimerRun(timer), 0, 60000);

		for(AbstractTask task : TaskList.periodList){
			timer.schedule(task, 0, Long.valueOf(task.period).longValue()*60000);
		}
		
	}

	private void stopMe() {
		timer.cancel();
	}

	protected static class TimerRun extends TimerTask {
		public TimerRun(Timer timer) {
			this.timer = timer;
		}

		private Timer timer;

		public void run() {
			Calendar c = Calendar.getInstance();
			int d = c.get(Calendar.DAY_OF_MONTH); // 1,
			int h = c.get(Calendar.HOUR_OF_DAY); // 0
			int m = c.get(Calendar.MINUTE); // 1

			String dd = (d < 10 ? "0" : "") + d;
			String hh = (h < 10 ? "0" : "") + h;
			String mm = (m < 10 ? "0" : "") + m;

			for (int i = 0, size = TaskList.timeList.size(); i < size; i++) {
				AbstractTask task = (AbstractTask) TaskList.timeList.get(i);
				if (task.time.indexOf("|" + mm + "|") != -1
						|| task.time.indexOf("|" + hh + ":" + mm + "|") != -1
						|| task.time.indexOf("|" + dd + " " + hh + ":" + mm
								+ "|") != -1) {
					timer.schedule(task, 0);
				}
			}
		}

	}
}
